import nodemailer from "nodemailer";
import { resolveYAML } from "./resolve-config-file";
import Mail from "nodemailer/lib/mailer";
import type SMTPTransport from "nodemailer/lib/smtp-transport";
import path from "path";

const authInfo = resolveYAML(path.resolve(__dirname, "../config/email.yaml"));

interface CompanyEmailSignature {
    name?: string; // 姓名
    department: string; // 部门
    company: string; // 公司
    phone?: string; // 电话
    email?: string; // 邮箱
    website?: string; // 网站
    address: string; // 地址
}
const defaultRecipientInfo: CompanyEmailSignature = {
    name: "IKUN1号",
    department: "练习部",
    company: "全名制作人无限公司",
    phone: "139 2312 4434",
    email: "ikun@sing.com",
    website: "www.ikun.com",
    address: "北京市朝阳区123号"
};

/**
 * 设置公司邮件签名
 * @param signature - 公司签名信息
 * @returns {string}html
 */
const setCompanyEmailSignature = (signature: CompanyEmailSignature = defaultRecipientInfo) => {
    return `
    <div>
        <div><span style="line-height: 1.6">----------------------------------------</span><br /></div>
        <div style="font-size: 14px; color: rgba(151, 151, 151, 1)">

            <b>${
                signature.name ? `<span style="color: #004d9a">${signature.name} &nbsp</span>` : ""
            }<span style="color: #d65819">${signature.department}</span></b
            ><br />

            <b><span>${signature.company}</span></b
            ><br />

            ${
                signature.phone
                    ? `<b><span>电话 phone：</span><span style="font-weight: normal">${signature.phone}</span></b
            ><br />`
                    : ``
            }

            ${
                signature.email
                    ? `<b><span>邮箱 E-mail：</span></b
            ><a href="${signature.email}" rel="noopener" target="_blank">${signature.email}</a><br />`
                    : ``
            }
            
            ${
                signature.website
                    ? `<b
                ><span>官网 Website：</span
                ><a href=" ${signature.website}" target="_blank" style="font-weight: normal"> ${signature.website}</a></b
            ><br />`
                    : ``
            }
            <b
                ><span>地址 Address：</span
                ><span style="font-weight: normal">${signature.address}</span></b
            ><br />
        </div>
    </div>
  `;
};

/*
 * 默认收件人信息
 */
const receiverInfo: Mail.Options = {
    // from: `"城"<${authInfo.user}>`,
    from: {
        name: "ikun",
        address: authInfo.user
    },
    subject: "ikun 训练营入营通知书",
    to: "2657234653@qq.com",
    html: `
   <h1>你好，你的唱跳rap程度符合本公司要求，请尽快加入我们吧。</h1>
    ${setCompanyEmailSignature()}
   `
};

/**
 * 创建一个SMTP客户端配置对象
 * @param {Object} options - 配置对象
 * @param options.service - 预设服务，默认支持的邮箱服务包括：”QQ”、”163”、”126”、”iCloud”、”Hotmail”、”Yahoo”等
 * @param options.host - 是要连接的主机名或 IP 地址（默认为“localhost”）
 * @param options.port – 是要连接到的端口（如果安全，则默认为 587，如果为 false，则默认为 465）
 * @param options.auth – 定义身份验证数据
 * @param auth.user – 发件人邮箱账号
 * @param auth.pass – 发件人邮箱的授权码 需要在自己的邮箱设置中生成，并不是邮件的登录密码
 * @param options.secure – 开启 TLS。在大多数情况下，如果要连接到端口 465，请将此值设置为 true。对于端口 587 或 25，请将其保留为 false
 */
const createTransportClient = (options: SMTPTransport.Options) => nodemailer.createTransport(options);

/**
 * 发送邮件
 * @param {string} service- 常见邮件服务，包括”QQ”、”163”、”126”、”iCloud”、”Hotmail”、”Yahoo”等
 * @param {import(Mail).Options} receiver - 收件人信息
 * @param receiver.from - 发件人邮箱，要求和客户端配置一致  `昵称<发件人邮箱>` 或 `{name: 昵称, address: 邮箱}`
 * @param receiver.to - 收件人邮箱，群发用数组 `xxx@qq.com`
 * @param receiver.text - 纯文本正文 `关山难越，谁悲失路之人；萍水相逢，尽是他乡之客。`
 * @param receiver.html - html 作为正文 `<p>sing dance rap</p>`
 * @param receiver.subject: - 主题 `滕王阁序`,
 * @param receiver.attachments - 附件
 * @param receiver.cc - 抄送 carbon copy
 * @param receiver.bcc - 密送 Blind carbon copy
 * @return {Promise} promise
 */
const sendMail = (receiver: Mail.Options = receiverInfo, service = "QQ") => {
    // 发件客户端配置
    const transporterOptions: SMTPTransport.Options = {
        service: service,
        auth: {
            user: authInfo.user,
            pass: authInfo.pass
        }
    };

    // 收件信息配置
    // from 必须和授权的 user 一样
    const fromType = typeof receiver.from;
    if (fromType === "undefined") receiver.from = authInfo.user;
    if (fromType === "string") {
        const sender = receiver.from as string;
        const index = sender.indexOf("<");
        receiver.from = index > 0 ? { name: sender.substring(0, index), address: authInfo.user } : authInfo.user;
    }
    if (fromType === "object") (receiver.from as any).address = authInfo.user;

    const transporter = createTransportClient(transporterOptions);
    return transporter.sendMail(receiver);
};

export { sendMail, setCompanyEmailSignature };
